package com.tf.integrated.controller;

import com.alibaba.fastjson.JSONObject;
import com.ccssoft.m8.common.ccssoft.modules.util.EntityWrapperHandle;
import com.ccssoft.m8.common.web.BaseController;
import com.tf.integrated.entity.EventresulttricyclesinfoEntity;
import com.tf.integrated.entity.SearchDataReturnEntity;
import com.tf.integrated.service.EventresultpedestriansinfoService;
import com.tf.integrated.service.EventresulttricyclesinfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 三轮车检索
 * @author allen
 * @date: 2020年9月14日上午10:56:20
 */
@Api(value = "三轮车检索",description="SearchTricycleController")
@RestController
public class SearchTricycleController extends BaseController
{
    @Autowired
    private EventresulttricyclesinfoService<EventresulttricyclesinfoEntity> tricycleService;

    @ApiOperation("三轮车检索")
    @GetMapping("/search/tricycles")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public SearchDataReturnEntity<JSONObject[]> searchDataList(@RequestParam Map<String, Object> data) {
        if (data != null && data.size() > 0) {
            String starttime=(String)data.get("starttime");
            String endtime=(String)data.get("endtime");
            String spage=(String)data.get("page");
            String ssize=(String)data.get("size");
            int page=0;
            int size=0;
            if(isExist(spage)&&isInteger(spage)){
                page=Integer.parseInt(spage);
            }
            if(isExist(ssize)&&isInteger(ssize)){
                size=Integer.parseInt(ssize);
            }
            int total=0;
            JSONObject[] arr=new JSONObject[0];
            if(isExist(starttime)&&isExist(endtime)&&page>=1&&size>0&&size<=200){
                int begin=(page-1)*size;
                int end=begin+size-1;
                EntityWrapperHandle<EventresulttricyclesinfoEntity> ew = new EntityWrapperHandle<EventresulttricyclesinfoEntity>();
                EntityWrapperHandle<EventresulttricyclesinfoEntity> ew3 = new EntityWrapperHandle<EventresulttricyclesinfoEntity>();
                ew.orderDesc(Collections.singletonList("id"));
                ew.last("limit "+(end+1));
                ew.between("createtime",starttime,endtime);
                ew3.between("createtime",starttime,endtime);
                String[] chnIds=getStringArray((String)data.get("chnId"));
                String[] hosts=getStringArray((String)data.get("host"));
                Integer[] manned=getIntArray((String)data.get("manned"));
                Integer[] convertible=getIntArray((String)data.get("convertible"));
                Integer[] roofcolor=getIntArray((String)data.get("roofcolor"));
                if(chnIds.length>0){
                    String sql=getSqlAndEqualOr("chn",chnIds);
                    ew.and(sql);
                    ew3.and(sql);
                }
                if(hosts.length>0){
                    String sql=getSqlAndEqualOr("deviceid",hosts);
                    ew.and(sql);
                    ew3.and(sql);
                }
                if(manned.length>0){
                    String sql=getJsonIdAndEqualOr("manned",manned);
                    ew.and(sql);
                    ew3.and(sql);
                }
                if(convertible.length>0){
                    String sql=getJsonIdAndEqualOr("convertible",convertible);
                    ew.and(sql);
                    ew3.and(sql);
                }
                if(roofcolor.length>0){
                    String sql= getJsonIdAndEqualOr("roofcolor",roofcolor);
                    ew.and(sql);
                    ew3.and(sql);
                }
                List<EventresulttricyclesinfoEntity> list = tricycleService.selectList(ew);
                total=tricycleService.selectCount(ew3);
                if(list!=null&&list.size()>0){
                    if (list.size() - 1 < begin) {
                        list.clear();
                    } else if (list.size() - 1 >= begin ) {
                        list=list.subList(begin,list.size());
                    }
                    arr=new JSONObject[list.size()];
                    for(int i=0;i<list.size();i++){
                        JSONObject json=new JSONObject();
                        json.put("id",list.get(i).getId());
                        json.put("Chn",list.get(i).getChn());
                        json.put("Convertible",list.get(i).getConvertible());
                        json.put("DriveWay",list.get(i).getDriveway());
                        json.put("FullPicPath",list.get(i).getFullpicpath());
                        json.put("Manned",list.get(i).getManned());
                        json.put("ObjPicPath",list.get(i).getObjpicpath());
                        json.put("Rect",list.get(i).getRect());
                        json.put("RoofColor",list.get(i).getRoofcolor());
                        json.put("Time",list.get(i).getTime());
                        json.put("Type",list.get(i).getType());
                        json.put("DeviceId",list.get(i).getDeviceid());
                        arr[i]=json;
                    }
                }
            }
            return new SearchDataReturnEntity<JSONObject[]>().ok(arr,200,total);
        }
        return new SearchDataReturnEntity<JSONObject[]>().error("size or page err");
    }

    public boolean isExist(String value){
        return value != null && !value.equals("") ;
    }

    public String[] getStringArray(String s){
        if(isExist(s)){
            return s.split(",");
        }
        return new String[0];
    }

    public Integer[] getIntArray(String s){
        if(!isExist(s)){
            return new Integer[0];
        }
        String[] str = s.split(",");
        List<Integer> list = new ArrayList<>();
        for (String value : str) {
            if (isInteger(value)) {
                list.add(Integer.parseInt(value));
            }
        }
        return list.toArray(new Integer[0]);
    }

    public boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    public String getSqlAndEqualOr(String field,String[] values){
        StringBuilder sql= new StringBuilder();
        sql.append("(");
        for(int i=0;i<values.length;i++){
            sql.append(field).append("='").append(values[i]).append("'");
            if(i<values.length-1){
                sql.append(" or ");
            }else{
                sql.append(")");
            }
        }
        return sql.toString();
    }

    public String getJsonIdAndEqualOr(String field,Integer[] values){
        StringBuilder sql= new StringBuilder();
        sql.append("(");
        for(int i=0;i<values.length;i++){
            sql.append("JSON_UNQUOTE(JSON_EXTRACT(").append(field).append(",'$.Id'))=").append(values[i]);
            if(i<values.length-1){
                sql.append(" or ");
            }else{
                sql.append(")");
            }
        }
        return sql.toString();
    }
}